<!--
 * @Description:
 * @Author: zhaolei
 * @Date: 2023-04-11 11:12:29
-->
<template>
  <el-dialog
    :title="isUpdateShelf ? '更新上架宠物' : '上架宠物'"
    :visible.sync="visible"
    width="60%"
    append-to-body
  >
    <el-steps
      :active="0"
      style="margin-bottom: 20px"
      simple
    >
      <el-step
        title="确认宠物基础信息"
        status="success"
        description=""
      ></el-step>
      <el-step
        title="填写宠物上架信息"
        :status="stepIndex === 0 ? 'wait' : 'success'"
        description=""
      ></el-step>
      <!-- <el-step
        title="推荐它喜欢的商品"
        :status="stepIndex === 2 ? 'success' : 'wait'"
        description=""
      ></el-step> -->
    </el-steps>
    <commonForm
      v-if="visible && stepIndex === STEP.INFO"
      :id="id"
      ref="commonForm"
      action="edit"
      @selectChange="selectChange"
    ></commonForm>
    <avue-form
      v-else-if="stepIndex === STEP.PUT_AWAY"
      ref="addForm"
      v-model="form"
      :option="tableOption"
      :upload-change="$uploadChange"
      :upload-exceed="uploadExceed"
      :upload-before="uploadBefore"
      :upload-error="uploadSizeError"
    >
      <template #personality="{ disabled }">
        <el-select
          v-model="form.personality"
          clearable
          :disabled="disabled"
          multiple
          placeholder="请选择性格标签"
        >
          <el-option
            v-for="item in personalityList"
            :key="item.attributeCode"
            :label="item.attributeName"
            :value="item.attributeCode"
          ></el-option>
        </el-select>
      </template>

      <template #areaId="{ disabled }">
        <el-select
          v-model="form.areaId"
          clearable
          :disabled="disabled"
          placeholder="请选择分配所属区域"
        >
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </template>

      <template #content>
        <el-autocomplete
          v-model="form.content"
          placeholder="请输入最近动态，如冬天的饭量增加了"
          style="width: 300px; margin-right: 12px"
          :maxlength="10"
          :fetch-suggestions="querySearch"
        ></el-autocomplete>
        <el-checkbox v-model="form.synchronization">
          若时间轴更新，后续则同步更新最近动态
        </el-checkbox>
        <div>
          PS：宠物被新主人领养成功后，会自动更新最新动态为：
          <span style="color: #00db68">被领养去新家啦</span>
        </div>
      </template>
    </avue-form>
    <like-goods
      v-else-if="stepIndex === STEP.LIKE_GOODS"
      :id="id"
      ref="likeGoods"
      @loading="(val) => (loading = val)"
      @success="submitSuccess"
    ></like-goods>
    <div class="flex-end">
      <el-button @click="visible = false">取消</el-button>
      <el-button
        v-if="stepIndex !== STEP.INFO"
        :loading="loading"
        @click="stepIndex -= 1"
      >
        上一步
      </el-button>
      <el-button
        class="btn"
        :loading="loading"
        type="primary"
        @click="confirm"
      >
        {{ toStepLabel(stepIndex) }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex';
import { tableOption } from '@/const/crud/pet/putAway';
import commonForm from './commonForm';
import {
  editObj,
  putAway,
  getShelfRecord,
  upPet,
  fetchCloudAreaListByBaseId,
} from '@/api/core/pet-file';
import { IS_SYNCHRONIZATION, BROADCAST_TYPE } from '@/const/type';
import { getListByTwoCode } from '@/api/core/classify';
import { remote } from '@/api/admin/dict';
import LikeGoods from './likeGoods.vue';
// import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';

const STEP = {
  INFO: 0, // 宠物基础信息
  PUT_AWAY: 1, // 宠物上架信息
  LIKE_GOODS: 2, // 推荐的商品
};

export default {
  name: 'putAwayPopup',
  components: { commonForm, LikeGoods },
  props: {
    id: {
      type: [Object, String],
    },
    value: {
      type: Boolean,
      default: false,
    },
    dataObj: { type: [Object] },
    isUpdateShelf: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      petInfo: null,
      STEP,
      stepIndex: STEP.INFO,
      form: {},
      loading: false,
      tableOption: tableOption('', false),
      fileList: [],
      // message: 'Click Start to Transcode',
      width: '',
      height: '',
      selectObj: {},
      arr: [],
      fileWH: [],
      personalityList: [],
      areaList: [],
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
    ...mapGetters(['userInfo', 'access_token']),
  },
  watch: {
    visible(val) {
      if (!val) {
        this.stepIndex = 0;
        this.$refs.addForm && this.$refs.addForm.resetForm();
        this.form = {};
      } else {
        this.$nextTick(() => {
          if (!this.isUpdateShelf) {
            this.$nextTick(() => {
              this.form.propagandaType = BROADCAST_TYPE.PICTURE;
            });
          } else {
            this.getShelfRecord();
          }
        });
      }
    },
    'form.petType': {
      immediate: true,
      async handler(val, oldVal) {
        const arr = ['personality'];
        if (val && val[0]) {
          arr.forEach((el) => {
            this.getListByTwoCode(val[0], el);
          });
        }
        if (this.validatenull(val)) {
          arr.forEach((el) => {
            this[`${el}List`] = [];
            this.form[el] = '';
          });
        }
        if (oldVal && oldVal[0] && val && val[0] && val[0] !== oldVal[0]) {
          arr.forEach((el) => {
            this.form[el] = '';
          });
        }
      },
    },
  },
  methods: {
    toStepLabel(index) {
      switch (index) {
        case STEP.INFO:
          if (this.isUpdateShelf) {
            return '保存基础信息，下一步';
          } else {
            return '保存基础信息，下一步';
          }
        case STEP.PUT_AWAY:
          if (this.isUpdateShelf) {
            return '保存上架信息并上架';
          } else {
            return '保存上架信息并上架';
          }
        // case STEP.LIKE_GOODS:
        //   if (this.isUpdateShelf) {
        //     return '更新商品';
        //   } else {
        //     return '保存商品信息并上架';
        //   }
        default:
          return '';
      }
    },
    async submitSuccess() {
      if (this.isUpdateShelf) {
        this.$message.success('操作成功！');
        this.$emit('success', true);
        this.visible = false;
      } else {
        try {
          this.loading = true;
          await upPet(this.petInfo.id);
          this.loading = false;
          this.visible = false;
          this.$message.success('操作成功！');
          this.$emit('success', true);
        } catch (err) {
          this.loading = false;
        }
      }
    },
    submit() {
      this.$refs.likeGoods.submit([this.petInfo.id]);
    },
    /*
     * @Description: 获取最近动态
     */
    async querySearch(queryString, cb) {
      const { data } = await remote('recent_dynamic');
      cb(
        data.data.map((item) => {
          return { value: item.description };
        })
      );
    },
    async getListByTwoCode(typeCode, attributeCode) {
      const res = await getListByTwoCode(typeCode, attributeCode);
      this[`${attributeCode}List`] = res.data.data;
    },
    selectChange(val) {
      this.selectObj = val;
      this.form.petType = [this.selectObj.typeCode, this.selectObj.varietyCode];
      this.form.$petType = [
        this.selectObj.typeName,
        this.selectObj.varietyName,
      ];
      this.getCloudAreaList(val.baseId);
    },

    getCloudAreaList(baseId) {
      fetchCloudAreaListByBaseId({ baseId }).then((res) => {
        this.areaList = res.data.data;
      });
    },
    async getShelfRecord() {
      const res = await getShelfRecord(this.id);
      if (res.data.data) {
        this.form = { ...res.data.data };
        this.form.synchronization =
          this.form.synchronization === IS_SYNCHRONIZATION.YES;
        const temp = JSON.parse(this.form.files);
        this.form.petFile = temp.map((item) => {
          let type = 'mov';
          if (item.type === 'image') {
            type = 'jpg';
          }
          return {
            ...item,
            url: `${item.url}?.${type}`,
          };
        });
        //
        this.form.petType = [this.form.typeCode, this.form.varietyCode];
        this.form.$petType = [this.form.typeName, this.form.varietyName];
        // 其他特征
        if (this.validatenull(JSON.parse(this.form.otherCharacteristics))) {
          this.form.otherCharacteristics = '';
        } else {
          this.form.otherCharacteristics = JSON.parse(
            this.form.otherCharacteristics
          ).map((item) => item.code);
        }
        // 基地状态/人气
        if (this.validatenull(JSON.parse(this.form.popularity))) {
          this.form.popularity = '';
        } else {
          this.form.popularity = JSON.parse(this.form.popularity).map(
            (item) => item.code
          );
        }
        // 性格标签
        if (this.validatenull(JSON.parse(res.data.data.personality))) {
          this.form.personality = [];
        } else {
          this.form.personality = JSON.parse(res.data.data.personality).map(
            (item) => item.code
          );
        }
      }
    },
    async uploadBefore(file, done, loading, column) {
      const flag = await this.getMp4Time(file);
      if (!flag) {
        loading();
        this.$message.warning('上传视频时长在三分钟以内！');
        return false;
      }
      const that = this;
      // 计算他的宽高
      this.imgchecked(file).then((data) => {
        //data返回值即为判断结果。
        that.fileWH.push({
          uid: file.uid,
          url: file.name,
          width: data.width,
          height: data.height,
        });
        done();
      });
    },
    //判断尺寸方法
    imgchecked(file) {
      return new Promise((resolve, reject) => {
        if (file.type.indexOf('image') !== -1) {
          //上传文件为图片类型
          const img = new Image();
          img.onload = function () {
            resolve(img);
          };
          img.src = URL.createObjectURL(file);
        } else {
          //上传文件为视频类型
          var videoUrl = URL.createObjectURL(file);
          var videoObj = document.createElement('video');
          videoObj.onloadedmetadata = function (evt) {
            URL.revokeObjectURL(videoUrl);
            videoObj.width = videoObj.videoWidth;
            videoObj.height = videoObj.videoHeight;
            // 执行上传的方法，获取外网路径，上传进度等
            resolve(videoObj);
          };
          videoObj.src = videoUrl;
          videoObj.load();
        }
      });
    },
    getMp4Time(file) {
      return new Promise((resolve) => {
        const fileExtend = file.name
          .substring(file.name.lastIndexOf('.'))
          .toLowerCase();
        //如果是mp4
        if (
          fileExtend === '.mp4' ||
          fileExtend === '.mpeg' ||
          fileExtend === '.WMV' ||
          fileExtend === '.mov'
        ) {
          //把element上传组件传给我们的file转成url
          const url = URL.createObjectURL(file);
          //获取mp4对象
          const v = document.createElement('video');
          v.src = url;
          //监听事件
          v.addEventListener('loadedmetadata', () => {
            //时间
            const time = Math.ceil(v.duration * 100) / 100;
            console.log('time', time, v.videoWidth, v.videoHeight);
            this.width = v.videoWidth;
            this.height = v.videoHeight;
            if (time > 4 * 60) {
              console.log('进来了码');
              resolve(false);
            } else {
              resolve(true);
            }
          });
        } else {
          //不是mp4
          resolve(true);
        }
      });
    },
    uploadSizeError(error, limitedSize) {
      // console.log(134, error, limitedSize);
      if (error === '文件太大不符合') {
        this.$message.warning(
          `文件大小不能超过${limitedSize.fileSize / 1024}M`
        );
      }
    },
    uploadExceed(limit, files, fileList, column) {
      this.$message.error(`只能上传${limit}个文件`);
    },
    transForm(arr) {
      const target = arr.map((el) => {
        // 针对已经处理过的数据，不再进行处理
        if (typeof el === 'string') {
          el = {
            url: el,
          };
        }
        if (el.type) {
          return el;
        }
        const suffix = el.url.substr(el.url.lastIndexOf('.') + 1).toLowerCase();
        let type = '';
        let poster = '';
        const imgSuffix = ['jpg', 'png', 'jpeg', 'webp', 'heic'];
        if (imgSuffix.includes(suffix)) {
          type = 'image';
          poster = el.url;
        } else {
          type = 'video';
          poster = `${el.url}?vframe/jpg/offset/0`;
        }
        //获取在上传前记录的宽、高
        const file =
          this.fileWH.find((item) => {
            return el.url.indexOf(item.uid + item.url) !== -1;
          }) || {};
        return {
          fileName: '',
          url: el.url,
          type,
          poster,
          width: file.width || 0,
          height: file.height || 0,
        };
      });
      return target;
    },
    confirm() {
      if (this.stepIndex === STEP.INFO) {
        this.confirmInfo();
      } else if (this.stepIndex === STEP.PUT_AWAY) {
        this.toList();
      } else {
        this.submit();
      }
    },
    transform(arr, target) {
      const that = this;
      const obj = {};
      arr.forEach((el) => {
        const temp = [];
        if (Array.isArray(target[el])) {
          target[el].forEach((v, k) => {
            // const dic = that.$refs.addForm[`${el}List`];
            const dic = that[`${el}List`];
            const label = dic.find(
              (item) => item.attributeCode === v
            ).attributeName;
            temp.push({ code: v, value: label });
          });
          obj[el] = JSON.stringify(temp);
        }
      });
      return obj;
    },
    async confirmInfo() {
      this.$refs.commonForm.$refs.addForm.validate(async (valid, done) => {
        if (valid) {
          this.loading = true;
          try {
            const dataObj = { ...this.$refs.commonForm.form };
            this.petInfo = dataObj;
            const params = { ...dataObj };
            const nameArr = dataObj.$petType.split(' | ');
            params.typeCode = dataObj.petType[0] || '';
            params.varietyCode = dataObj.petType[1] || '';
            params.typeName = nameArr[0] || '';
            params.varietyName = nameArr[1] || '';
            delete params.otherCharacteristics;
            if (dataObj.isUnknownTime) {
              params.birthDay = null;
            } else {
              params.birthDay = dataObj.birthDay.substr(0, 10) + ' 00:00:00';
            }
            if (dataObj.receiveDate) {
              params.receiveDate =
                dataObj.receiveDate.substr(0, 10) + ' 23:59:59';
            }
            if (params.petType) {
              params.petType = JSON.stringify(params.petType);
            }
            params.id = this.id;
            await editObj(params);
            this.$message.success('操作成功');
            done();
            this.loading = false;
            this.stepIndex += 1;
            // this.visible = false;
            // this.$emit('success', true);
          } catch (error) {
            done();
            this.loading = false;
            throw new Error(error);
          }
        }
      });
    },
    toList() {
      this.$refs.addForm.validate(async (valid, done) => {
        if (valid) {
          this.loading = true;
          try {
            let params = { ...this.form };
            params = {
              labelValue: params.labelValue,
              content: params.content,
              files: params.files,
              likeChildren: params.likeChildren,
              likeOtherPets: params.likeOtherPets,
              introduction: params.introduction,
              synchronization: params.synchronization,
              otherCharacteristics: params.otherCharacteristics,
              personality: params.personality,
              popularity: params.popularity,
              $otherCharacteristics: params.$otherCharacteristics,
              $personality: params.$personality,
              $popularity: params.$popularity,
              id: this.id,
            };
            // 是否同步动态
            params.synchronization = params.synchronization
              ? IS_SYNCHRONIZATION.YES
              : IS_SYNCHRONIZATION.NO;
            // 其他特征
            if (this.validatenull(params.otherCharacteristics)) {
              params.otherCharacteristics = JSON.stringify([]);
            } else {
              const otherCharacteristics =
                params.otherCharacteristics instanceof Array
                  ? params.otherCharacteristics
                  : params.otherCharacteristics.split(',');
              params.otherCharacteristics = JSON.stringify(
                otherCharacteristics.map((item, index) => {
                  const valueArr = params.$otherCharacteristics.split(' | ');
                  return {
                    code: item,
                    value: valueArr[index],
                  };
                })
              );
            }
            // 转换欢迎程度
            if (this.validatenull(params.popularity)) {
              params.popularity = JSON.stringify([]);
            } else {
              const popularity =
                params.popularity instanceof Array
                  ? params.popularity
                  : params.popularity.split(',');
              params.popularity = JSON.stringify(
                popularity.map((item, index) => {
                  const valueArr = params.$popularity.split(' | ');
                  return {
                    code: item,
                    value: valueArr[index],
                  };
                })
              );
            }
            // 性格特征
            if (this.validatenull(params.personality)) {
              params.personality = JSON.stringify([]);
            } else {
              params.personality = JSON.stringify(
                params.personality.map((item) => {
                  return {
                    code: item,
                    value: this.personalityList.find(
                      (pItem) => pItem.attributeCode === item
                    ).attributeName,
                  };
                })
              );
            }
            const attr = this.form.petFile.map((item) => {
              if (typeof item === 'string') {
                item = {
                  url: item,
                };
              }
              return {
                ...item,
                url: item.url.replace(/\?.*$/, ''),
              };
            });
            const target = await this.transForm(attr);
            params.coverImage = `${target[0].poster}`;
            params.files = JSON.stringify(target);
            params.areaId = this.form.areaId;
            params.meaning = this.form.meaning;
            await putAway(params);
            const tip = '操作成功';
            this.$message.success(tip);
            this.$emit('success', true);
            this.visible = false;
            done();
            this.loading = false;
            // this.stepIndex += 1;
            this.$alert(
              '所有视频需在后端进行转码处理，若该条宠物仍为“待上架”状态，请稍后重新刷新列表查看最新上架状态！',
              '提示',
              {
                confirmButtonText: '我已知晓，不再提醒',
                callback: (action) => {},
              }
            );
          } catch (error) {
            done();
            this.loading = false;
            throw new Error(error);
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
